//
//  Collection.m
//  MHO
//
//  Created by papo on 3/13/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "Collection.h"
#import "Lib.h"
#import "ServiceLib.h"
#import "SBJson.h"
#import "Application.h"

@implementation Collection

+ (NSArray*)getCollectionFromUrl:(NSString *)url {
    return [self getCollectionFromUrl:url addFavorite:NO];
}

+ (NSArray*)getCollectionFromUrl:(NSString *)url addFavorite:(BOOL)add{
    
    NSString* retVal = [ServiceLib sendGetRequest:url];
    NSMutableArray* array = [NSMutableArray array];
    if (add) {
        Collection* favorite = [[Collection alloc] init];
        favorite.colletionId = @(0);
        favorite.collectionName = @"Yêu thích";
        //    favorite.
        [array addObject:favorite];
    }
    if (retVal) {
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        NSDictionary* dict = [parser objectWithString:retVal];
        if (dict) {
            NSArray* list = [dict objectForKey:@"DataList"];
            if (list && ![list isKindOfClass:[NSNull class]]) {
                for (NSDictionary* d in list) {
                    if (d) {
                        Collection* col = [[Collection alloc] initWithDictionary:d];
                        [array addObject:col];
                    }
                }
            }
        }
    }
    
    return array;
}

+ (void)updateCollection:(Collection *)collection type:(NSInteger)type{
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/ChuDe?Type=%ld&Id=%@&IdSystem=2&Email=%@&Name=%@&Des=%@&key=%@", (long)type, collection.colletionId, collection.userEmail, collection.collectionName, collection._description, kServerKey];
    
    NSString* retVal = [ServiceLib sendGetRequest:url];
    if (retVal) {
        
    }
    
}

+ (void)deleteCollection:(Collection *)collection {
    [self updateCollection:collection type:3];
}

+ (void)updateCollection:(Collection *)collection {
    [self updateCollection:collection type:2];
}

+ (void)createNewCollection:(Collection *)collection {
    [self updateCollection:collection type:1];
}

- (id)initWithDictionary:(NSDictionary *)dict {
    if (self = [super init]) {
        self.colletionId = numberCheckNull([dict objectForKey:@"Id"]);
        self.collectionName = strCheckNull([dict objectForKey:@"Name"]);
        self.userEmail = strCheckNull([dict objectForKey:@"User"]);
        self._description = strCheckNull([dict objectForKey:@"Des"]);
        self.views = numberCheckNull([dict objectForKey:@"Views"]);
    }
    return self;
}
@end
